<?php

namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Controller;
use think\Request;
use think\Db;
use think\db\Query;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory; 
use PhpOffice\PhpSpreadsheet\Cell\Coordinate; 

class GradeController extends AdminBaseController
{
    //显示
    public function index()
    {
        //接收数据
        $name=$this->request->param('name');
        //连接数据库可以去掉表前缀的数据库表名。这个方法会自己去读取数据库配置文件中的表前缀那个配置
        $grade=Db::name('grade')
            //表连接
            ->join('cmf_subject','cmf_subject.id=cmf_grade.subject_id')
            ->join('cmf_student','cmf_student.id=cmf_grade.student_id')
            ->field('cmf_subject.name as subject_name,cmf_student.name as student_name,cmf_grade.*')
            //接收所查询的班级名称的值
            ->where(function(Query $query) use ($name){
                //模糊查询
                if($name){
                    $query->where('cmf_grade.name','like',"%$name%");
                }
            })
            ->order("id DESC")//根据学校ID，倒序（ASC为正序）
            //1.分页:每三行为一个页面;2.保持页面稳定性//3.接收全部数据
            ->paginate(5,false,$this->request->param());
        //获取分页数据
        $page=$grade->render();
        //1.渲染页面2.接收返回的值
        return view('index',['grade'=>$grade,'page'=>$page]);
    }

    //添加
    public function add()
    {
        if (request()->isPost()) {
            $add = Db::name('grade')->insert(input());
            if ($add) {
                $this->success('添加成功','grade/index');
            } else {
                $this->error('添加失败');
            }
        }
        $subject = Db::name('subject')->select();
        $student = Db::name('student')->select();
        return view('grade_add',['subject'=>$subject,'student'=>$student]);
    }

    //修改
    public function edit($id)
    {
        if (request()->isPost()) {
            $data = input();
            $edit = Db::name('grade')->update($data, ['id' => $data['id']]);
            if ($edit) {
                $this->success('修改成功','grade/index');
            } else {
                $this->error('修改失败');
            }
        }
        $id = input('id');
        $grade = Db::name('grade')->get($id);
        $subject = Db::name('subject')->all();
        $student = Db::name('student')->all();
        return $this->fetch('grade_edit', [
            'data' => $grade,
            'subject'=>$subject,
            'student'=>$student]);
    }

    //删除
    public function delete()
    {
        $id = $this->request->param('id');
        if(Db::name('grade')->delete($id) !== false){
            $this->success('删除成功','grade/index');
        }else {
            $this->error('删除失败');
        }
    }

    //多选删除
    public function delAll()
    {
        $ids = input('ids/a');
        $del = Db::name('grade')->delete($ids);
        if ($del){
            return ['code'=>200,'msg'=>'删除成功'];
        }else{
            return ['code'=>100,'msg'=>'删除失败'];
        }
    }

    //导出Excel
    public function exportExcel()
    {
        // 查询要导出的数据
        $data = Db::name('grade')
            ->join('cmf_subject','cmf_subject.id=cmf_grade.subject_id')
            ->join('cmf_student','cmf_student.id=cmf_grade.student_id')
            ->field('cmf_subject.name as subject_name,cmf_student.name as student_name,cmf_grade.*')
            ->select();
        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动单元格
        $sheet = $spreadsheet->getActiveSheet();

        // 获取单元格
        $cellA = $sheet->getCell('A1');
        // 设置单元格的值
        $cellA->setValue('ID');
        // 设置 A 列 列宽
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('学生姓名');
        $sheet->getColumnDimension('B')->setWidth(10);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('所有课程');
        $sheet->getColumnDimension('C')->setWidth(10);

        $cellD = $sheet->getCell('D1');
        $cellD->setValue('成绩');
        $sheet->getColumnDimension('D')->setWidth(10);

        // 设置样式 标题
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);
        $sheet->getStyle('D1')->applyFromArray($styleArray);

        // 从 A2 开始填充数据
        foreach ($data as $k => $v) {
            $n = $k + 2;
            // 获取单元格
            $cellA = $sheet->getCell('A'.$n);
            // 设置单元格的值
            $cellA->setValue($v['id']);

            $cellB = $sheet->getCell('B'.$n);
            $cellB->setValue($v['student_name']);

            $cellC = $sheet->getCell('C'.$n);
            $cellC->setValue($v['subject_name']);

            $cellD = $sheet->getCell('D'.$n);
            $cellD->setValue($v['name']);

            // 再给表格体设置样式
            $sheet->getStyle('A'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('B'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('C'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('D'.$n)->applyFromArray($styleArrayBody);
        }

        $file_name = '学生成绩列表.xlsx';
        // 实例化导出类
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename='.$file_name);
        header('Cache-Control:max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    // 从 Excel 导入数据
    public function importExcel()
    {
        // 接收文件
        $file = $_FILES['file']['tmp_name'];
        // 创建读操作
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        // 打开文件、载入excel表格
        $spreadsheet = $reader->load($file);
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();

        // 获取总列数
        //$highestColumn = $sheet->getHighestColumn();
        // 获取总行数
        $highestRow = $sheet->getHighestRow();
        //halt($highestRow);
        // 将列转为数字
        //$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

        // 存放插入成功的记录
        $successLog = [];
        // 存放插入失败的记录
        $failLog = [];

        // 从第二行开始读取表格数据，循环写入数据库
        for ($i = 2; $i <= $highestRow; $i++) {
            // 第 1 次循环获取第 3 列 第 2 行单元格的值，第 2 次循环获取第 3 列 第 3 行单元格的值
            $student_name = $sheet->getCellByColumnAndRow(2,$i)->getValue();
            $subject_name = $sheet->getCellByColumnAndRow(3,$i)->getValue();
            $name = $sheet->getCellByColumnAndRow(4,$i)->getValue();
            $data = [
                'student_id' =>$student_name,
                'subject_id' => $subject_name,
                'name' => $name,
            ];
            $insert = Db::name('grade')->insert($data);
            if ($insert) {
                $successLog[] = '第'.$i.'条，插入成功';
            } else {
                $failLog[] = '第'.$i.'条，插入失败';
            }
        }
        // 将成功数和失败数返回给 ajax
        return json(['success' => count($successLog), 'fail' => count($failLog)]);
    }
}